package org.blogspot.t0yv0.marcalog.controller

import com.google.appengine.api.blobstore._
import org.blogspot.t0yv0.marcalog.model._
import org.blogspot.t0yv0.marcalog.util._

sealed class InsertTask(load: String) extends Task {

  def this()              = this("")
  override val payload    = Some(load)

  override def execute(ctx: HttpContext, pm: DataManager) {
    val r = ctx.request.getReader;
    val people = List.newBuilder[Person];
    val items  = List.newBuilder[Item];
    def process(title: String, person: String, isbn: String) = {
      title match {
        case "" => {};
        case t  => {
          val p =
            person match {
              case "" => None;
              case n  => {
                val p = new Person(n);
                people += p;
                Some(p)
              }
            }
          items += new Item(t, p, Util.parseISBN(isbn));
        }
      }  
    }
    def loop {
      r.readLine match {
        case null  => {}
        case title => {
          val person = r.readLine;
          val isbn   = r.readLine;
          process(title, person, isbn);
          loop;
        }
      }
    }
    loop;
    pm.insert(people.result);
    pm.insert(items.result);
  }
}
